當使用者輸入資料時,若不小心輸入跳脫字元 Escape Character,如 \n or \t 等時,在資料處理與儲存時,應該要過濾,避免日後使用者查不到該資料 (或其它問題),進而衍伸客服 (or Bug)
Ruby 內建 strip 這方法,可以用過該方法過濾
$ irb
"  hello\t"
# "  hello\t"
"  hello\t".strip
# "hello"
使用 strip_attributes Gem,可參考此 commit
# 在想使用的 Model 中加入 (以 shop 為例)
# app/models/shop.rb
class Shop < ApplicationRecord
  strip_attributes
end
---
# 寫個測試覆蓋
# spec/models/shop_spec.rb
require 'rails_helper'
RSpec.describe Shop, type: :model do
  describe "#strip_attributes" do
    context "note" do
      subject do
        shop = Shop.new(name: "TEST", email: "TEST", note: "TEST\n")
        shop.valid?
        shop.note
      end
      it { is_expected.to eq("TEST") }
    end
  end
end
鐵人賽文章連結:https://ithelp.ithome.com.tw/articles/10264570
medium 文章連結:https://link.medium.com/tBNoHEh2Mjb
本文同步發布於 小菜的 Blog https://riverye.com/
備註:之後文章修改更新,以個人部落格為主